from flask import Flask, jsonify, request
from flask_mongoengine import MongoEngine
import json
# 实例化flask服务器对象
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'test',
    'host': 'localhost',
    'port': 27017
}
# 定义路由
db = MongoEngine()
db.init_app(app)

class User(db.Document):
    name = db.StringField()
    email = db.StringField()
    

@app.route('/', methods=['GET'])
def hello_world():
    return 'Hello World!'

@app.route('/', methods=['GET'])
def query_records():
    name = request.args.get('name')
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        return jsonify(user.to_json())
@app.route('/', methods=['PUT'])
def create_record():
    record = json.loads(request.data)
    user = User(name=record['name'],
                email=record['email'])
    user.save()
    return jsonify(user.to_json())
@app.route('/', methods=['POST'])
def update_record():
    record = json.loads(request.data)
    user = User.objects(name=record['name']).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.update(email=record['email'])
    return jsonify(user.to_json())
@app.route('/', methods=['DELETE'])
def delte_record():
    record = json.loads(request.data)
    user = User.objects(name=record['name']).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.delete()
    return jsonify(user.to_json())


if __name__ == '__main__':
    # debug模式开启服务
    app.run(debug=True)
    user = User()
    # 增加
    user(name='test',email='fsdhfjsd@hfks.con').save()
    # 查询
    test = User.objects(name='test').first()
    print(test)
    
    
    # 改 
    test.update(name='test1')
    print(test)
    # 删除
    test.delete()
    # 注意：改，删除必须建立在查询的基础上
